package multitionPattern;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 按需创建的多例模式
 */
public class LazyMultiton {
    private static final int MAX_INSTANCES = 5;
    private static final Map<String, LazyMultiton> instances = new ConcurrentHashMap<>();
    
    private final String key;
    private final long creationTime;
    
    private LazyMultiton(String key) {
        this.key = key;
        this.creationTime = System.currentTimeMillis();
        System.out.println("创建多例实例，键: " + key);
    }
    
    public static LazyMultiton getInstance(String key) {
        if (instances.size() >= MAX_INSTANCES && !instances.containsKey(key)) {
            throw new IllegalStateException("已达到最大实例数量: " + MAX_INSTANCES);
        }
        
        return instances.computeIfAbsent(key, k -> new LazyMultiton(k));
    }
    
    public static boolean containsKey(String key) {
        return instances.containsKey(key);
    }
    
    public static int getInstanceCount() {
        return instances.size();
    }
    
    public String getKey() {
        return key;
    }
    
    public long getCreationTime() {
        return creationTime;
    }
    
    public void process(String data) {
        System.out.println("实例 " + key + " 处理数据: " + data);
    }
}